package com.delivery.deliverysystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.delivery.deliverysystem.exception.RException;
import com.delivery.deliverysystem.pojo.DO.NumberRule;
import com.delivery.deliverysystem.service.NumberRuleService;
import com.delivery.deliverysystem.dao.NumberRuleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @author Administrator
* @description 针对表【number_rule(送货单号的编号规则表)】的数据库操作Service实现
* @createDate 2025-05-06 21:12:06
*/
@Service
public class NumberRuleServiceImpl extends ServiceImpl<NumberRuleMapper, NumberRule>
    implements NumberRuleService{

    @Autowired
    private NumberRuleMapper numberRuleMapper;

    @Override
    public String getNumberRule() {
        List<NumberRule> numberRules = numberRuleMapper.selectList(null);
        StringBuilder stringBuilder = new StringBuilder();
        for(NumberRule numberRule:numberRules){
            if(numberRule.getStatus()==1){
                stringBuilder.append(numberRule.getSymbol());
            }
        }
        return stringBuilder.toString();
    }

    @Override
    public String updateRule(String numberRuleList) throws RException {
        List<NumberRule> numberRules = numberRuleMapper.selectList(null);
        Map<String,NumberRule> map  = new HashMap<>();
        for(NumberRule rule:numberRules){
            map.put(rule.getSymbol(),rule);
        }
        //将传入的字符串按逗号分割并为每个符号添加方括号
        String[] parts = numberRuleList.split(",");
        List<String> symbolsWithBrackets = Arrays.stream(parts)
                .map(part -> "[" + part + "]")
                .collect(Collectors.toList());
        List<String> symbols = Arrays.asList("[CN]","[YYYY]","[YY]","[MM]","[DD]","[NUM]");
        for(String symbol:symbols){
            NumberRule numberRule = map.get(symbol);
            if(numberRule==null){
                throw new RException("编号规则符号不存在",500);
            }
            if(symbolsWithBrackets.contains(symbol)){
                numberRule.setStatus(1);
            }else{
                numberRule.setStatus(0);
            }
        }
        for(NumberRule rule:numberRules){
            if(numberRuleMapper.updateById(rule)<0) throw new RException("更新编号规则失败",500);
        }
        return getNumberRule();
    }
}




